<?php
namespace app\html5\controller;

use think\facade\Db;
use think\facade\Cache;
use app\BaseController;
use EasyWeChat\Factory;

class Weixin extends BaseController
{
    public function __construct()
    {
        // 测试号
//        $this->appid = 'wx4c004aac08dd5e82';
//        $this->appsecret = '3fb483306a4932cff567b06c1db0448e';
        // 泰心堂
        $this->appid = 'wxee9d276ea7f8e232';
        $this->appsecret = '105db963ab7d8628ca0cac4b955ec6b1';

        $this->config = [
            'app_id' => 'wxee9d276ea7f8e232',
            'secret' => '105db963ab7d8628ca0cac4b955ec6b1',
            'token' => 'yikangbao',
            'response_type' => 'array',
            //...
        ];
    }
    // 微信服务接口验证
    public function check_api()
    {
        $app = Factory::officialAccount($this->config);

        $response = $app->server->serve();

        // 将响应输出
        return $response->send();
    }
    // 微信公众号获取openid登录
    public function oauth2_login()
    {
        $backurl = input('backurl');

        if ($backurl) {
            $jump_id = md5(time().'_'.rand(1000000,9999999));

            $redis = Cache::store('redis');
            $r_data = [
                'backurl'=>$backurl
            ];

            $json = json_encode($r_data);
            $redis->set('JUMPID:'.$jump_id, $json,60);
            $this->get_base_code($jump_id,'snsapi_base');
        }
    }
    // 微信公众号获取openid创建账号
    public function oauth2_add_user()
    {
        $auth_token = input('auth_token');
        $backurl = input('backurl');

        $redis = Cache::store('redis');
        $auth_token_val = $redis->get('AUTH_KEY:'.$auth_token);

        // 存在鉴权秘钥，获取openid，然后创建账号
        if($auth_token_val){
            $backurl = input('backurl');
            $type = input('type');
            $auth_token = input('auth_token');

            if ($backurl) {
                $jump_id = md5(time().'_'.rand(1000000,9999999));

                $redis = Cache::store('redis');
                $r_data = [
                    'backurl'=>$backurl,
                    'type'=>1,
                    'user_type'=>$type,
                    'auth_token'=>$auth_token
                ];

                $json = json_encode($r_data);
                $redis->set('JUMPID:'.$jump_id, $json,60);
                $this->get_base_code($jump_id,'snsapi_base');
            }
        }else{
            echo '<script>alert("参数错误")</script>';die;
        }


    }

    public function get_base_code($jump_id,$scope)
    {
        $appid = $this->appid;
        $state = $jump_id;

        $redirect_uri = request()->domain().'/index.php/html5/weixin/getopenid';
        $oauthurl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
        header('Location: '.$oauthurl);
        exit;
    }

    public function getopenid()
    {
        $code = input('code');
        $jump_id = $state = input('state');
        $appid = $this->appid;
        $appsecret = $this->appsecret;

        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';

        // 获取access_token
        $res = json_decode(file_get_contents($url),true);

        $openid = $res['openid'];


//        $openid = 'o_X7m5mjmsxAidOubFzW_uVtMX7A';

        $redis = Cache::store('redis');

        $jump_data = json_decode($redis->get('JUMPID:'.$jump_id),true);

        $userinfo = Db::table('user_doc')->where('openid', $openid)->find();
//        print_r($userinfo);die;

        if (!isset($userinfo['id'])) {
            if(isset($jump_data['type'])){
                $openid = $res['openid'];
                $userinfo_data['openid'] = $openid;
                // 指定身份
                $userinfo_data['type'] = $jump_data['user_type'];

                Db::table('user_doc')->insert($userinfo_data);

                $userinfo = Db::table('user_doc')->where('openid', $openid)->find();

//                    print_r([$openid,$id]);die;
            }else{
                exit('<script>alert("您没有权限登录，请联系医康宝负责人邀请");window.close();</script>');
            }
        }

        $id = $userinfo['id'];

        $backurl = $jump_data['backurl'];

//        print_r($id);die;
        $token = login_token($id);
        $location = $backurl.'/#/pages/index/index?token='.$token;

        header('Location: '.$location);
        exit;
    }

    public function send_gzhmessage($openid)
    {
        // $openid = 'ote8Q6TvHySzHKn7vwmwaRLip6Zo';
        $tid = 'EL5sEiXbcouhWgy00h2NAhKpbpgh2lB_TJrAZvnw6sY';
        $access_token = $this->get_access_token();
        $gourl = 'http://jlpa.miaosu8.cn/index.html';

        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token;
        $appid = $this->appid;

        $send_data['touser'] = $openid;
        $send_data['template_id'] = $tid;
        $send_data['url'] = $gourl;
        $send_data['miniprogram'] = [];
        $send_data['data']['first']['value'] = '问题的名称或进度';
        $send_data['data']['keyword1']['value'] = '项目的名称';
        $send_data['data']['keyword2']['value'] = '提出人';
        $send_data['data']['keyword3']['value'] = '指向人';
        $send_data['data']['keyword4']['value'] = '待处理/已处理/未通过';
        $send_data['data']['keyword5']['value'] = '2021/8/27';
        $send_data['data']['remark']['value'] = '请尽快处理';

        $send_data = json_encode($send_data);
        $res = http_request($url,$send_data);
        return $res;

    }

    public function start_wx()
    {
        $taskid = input('task_id');
        $reason = input('reason');
        $proid = Db::name('think_task')->where('id',$taskid)->value('proid');
        $uidlist = Db::name('think_user_pro')->where('proid',$proid)->whereIn('add_pro_approval',[0,3])->column('uid');
        $touser = [];

        for($x = 0;$x < count($uidlist);$x++){
            $openid = Db::name('think_user')->where('id',$uidlist[$x])->value('openid');
            if($openid){
                array_push($touser,$openid);
            }
        }
        foreach($touser as $key => $val){
            $data = $this->send_gzhmessage($val);
        }
        if($data){
            return rejson(20000,'推送成功');
        }

    }

    //获取access_token
    public function get_access_token()
    {
        $access_token = Db::name('think_access_token')->where('id','1')->find();
        $time = time();
        if(!$access_token['value'] || $access_token['end_time'] <= $time){
            $appid = $this->appid;
            $appsecret = $this->appsecret;
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;

            $res = json_decode(file_get_contents($url),true);
            if($res['access_token']){
                $num = Db::name('think_access_token')->where('id','1')->update(['value' => $res['access_token'],'end_time' => ($time + 7000)]);
                if($num){
                    return $res['access_token'];
                }
            }
        }else{
            return $access_token['value'];
        }
    }
}
